#include <jni.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <unistd.h>
#include <strings.h>

#define BAUDRATE B115200

int fd = -2;
char filename[30];
struct termios newtio;

int myopen(void)
{
	int res;

    bzero(&newtio, sizeof(newtio));
    newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
	newtio.c_lflag = 0;
	newtio.c_cc[VTIME] = 10;   
    newtio.c_cc[VMIN] = 1;   

    fd = open(filename, O_RDWR | O_NOCTTY);
    if (fd <0) {
    	return (-1);
    }
	res = tcflush(fd, TCIFLUSH);
	if (res < 0)
	{
		fd = -2;
		return -2;
	}
		
    res = tcsetattr(fd, TCSANOW, &newtio);
	if (res < 0)
	{
		fd = -2;
		return -3;
	}

	return 0;
}

void myclose(void)
{
	if (fd >= 0)
	{
		close(fd);
	}
	return;
}

int myread(unsigned char *data)
{
	int 			res;

	if (fd < 0)
	{
		return -3;
	}
	res = read(fd, data, 1);

	return res;
}

int mywrite(unsigned char data)
{
	int res;
	if (fd < 0)
	{
		return -3;
	}
	res = write(fd, &data, 1);
	return res;
}

void Java_com_phychips_JniClass_serialClose(JNIEnv *env, jobject thiz)
{
	return myclose();
}


jint Java_com_phychips_JniClass_serialOpen(JNIEnv *env, jobject thiz, jbyteArray array, jint length)
{
	int i;
	jbyte *nam;


	nam = (*env)->GetByteArrayElements(env, array, 0);
	for (i=0; i<length; i++)
	{
		filename[i] = (char) nam[i];
	}
	filename[i] = '\0';
	(*env)->ReleaseByteArrayElements(env, array, nam, 0);
	return myopen();
}


jint Java_com_phychips_JniClass_serialRead(JNIEnv *env, jobject thiz)
{
	int 			result;
	unsigned char 	data = 1;

	result = myread(&data);
	
	if (result < 0)
	{
		return -1;
	}
	else
	{
		result = data;
		return result;
	}
}


jint Java_com_phychips_JniClass_serialWrite(JNIEnv *env, jobject thiz, jint data)
{
	unsigned char 	byte;
	int				res;

	byte = (unsigned char) (data & 0xFF);
	
	res = mywrite(byte);
	
	if (res <= 0)
	{
		return -1;
	}
	return 0;
}

void Java_com_phychips_JniClass_test(JNIEnv *env, jobject thiz)
{
	return;
}


